<?php

class Order_Service_OrderProccess {
	protected $_order = null;
	protected $_orderCode = null;
	protected $_plan = null;
	protected $_customerId = null;
	protected $_procCnt = null;
	protected $_products = null;
	protected $_orderShip = null;
	protected $_chargeBalance = 0; //扣取费用
	protected $_isDispatch = false; //是否有分开（套餐/Balance）扣取
	protected $_chargeBalanceCurrency = null;
	protected $_outOfStock = false;
	protected $_outOfBalance = false;
	public $_error = null;
	protected $_warning = null;
	protected $_customer = null;
	protected $_volume = null;
	protected $_weight = null;
	protected $_shipFee = null;
	protected $_shipFeeCurrencyCode = null;
	public $_shipOrder = '';
	protected $_status = null;
	protected $_refTracking = null;
	protected $_checkOutOfStock = false;
    protected $_rule=1;//申报价值

	public function __construct($orderCode) {
		if (isset ($orderCode)) {
			$this->_orderCode = $orderCode;
			$this->setOrder();
			$this->setCustomer();
			$this->getShipTypeCode();
		}
	}
	
	/*
	*判断是否扣物流费用
	*return true=>不扣费, false=>正常扣费
	*/
	 private function getCheckFee(){
		if($this->_order['shipping_method']=='SELFPICKUP'){
			return true;
		}
		return false;
	 }
	 
	/*
	*运输方式分类的code
	*/
	 private function getShipTypeCode(){
		$this->_order['ship_type_code'] = "N";
		if($this->_order['shipping_method']){			
			$shiptype =Shipping_Service_ShipType::getByValue($this->_order['shipping_method'],"st_code");
			
			$this->_order['ship_type_code'] = $shiptype&&in_array($shiptype['st_class_code'],array('CRP','CPS'))?"Y":"N";//平邮和挂号需要			
//			print_r($shiptype);
//			print_r($this->_order['ship_type_code']);
//			exit;
		}
	 }
	/**
	* 绑定物流订单
	*/
	public function boundOrder() {
	    $lang = Zend_Registry::get('lang');
		if (empty ($this->_shipOrder)) {
			throw new Exception($lang['ship_code_create_fail']);
		}
        $osStatus=2;
        if($this->_refTracking=='EPACKET' || ($this->_refTracking == $this->_order['orders_code'] && $this->_order['shipping_method']=='EPACKET') ){
            $osStatus=9;  //没有返回跟踪号
            $this->_refTracking='EPACKET';
        }
		$orderShipRow = array (
			"orders_code" => $this->_order['orders_code'],
			"warehouse_id" => $this->_order['warehouse_id'],
			"carrier_code" => 'SFC',
			"tracking_number" => $this->_shipOrder,
			"os_status" => $osStatus ,
			"os_declared_value" => $this->_order['parcel_declared_value'],
			//"os_guarantee_value" => $this->_order['guarantee_value'],
			"os_shipping_fee_estimate" => $this->_order['shipping_fee_estimate'],
			"os_create_date" => date("Y-m-d H:i:s")
		);
		if($this->_refTracking!='') $orderShipRow['ref_tracking_number'] = $this->_refTracking;
		$model = new Order_Model_OrderShip();
		//先将之前的数据更新状态为0，再创建!
		$model->updateByOrdersCodeAndOsid(array('os_status'=>0,'os_last_update'=>date('Y-m-d H:i:s')),$this->_order['orders_code'],0);
		if (!$model->create($orderShipRow)){
			throw new Exception($lang['ship_code_create_fail']);
		}
	}
	

	public function setSenderInfo() {
		if (empty ($this->_addressBook)) {
			$addressBookModel = new Customer_Model_CustomerAddressBook();
			$addressBook = $addressBookModel->getByTypeAndCustomerId(3, $this->_order['customer_id']);
			$this->_addressBook = $addressBook;
		}
	}

	public function setCountry() {
		if (empty ($this->_country)) {
			$countryModel = new Common_Model_Country();
			$country = $countryModel->getByValue($this->_order['consignee_country_id']);
			$this->_country = $country;
		}
	}
// $wpu_proc_type-->0:扣减库存;1:增加库存;2:冻结库存
	public function createUsage($wpbId,$wpu_proc_type,$quantity,$editquantity,$note){
		//添加使用日志
	    $lang = Zend_Registry::get('lang');
		$addWSP=array(
				'wpu_type'=>0,
				'wpu_proc_type'=>$wpu_proc_type,
				'wpu_refId'=>$this->_orderCode,
				'wpu_quantity'=>abs($editquantity),
				'wpu_note'=>$note,
				'wpb_id'=>$wpbId,
		);
		
		$addWSP['wpu_current_qty']=$quantity;
		if(!Warehouse_Service_ProductUseage::create($addWSP)){
			throw new Exception("".$this->_orderCode."   ".$lang['order_product_pickup_log_fail']);
		}
		
	}
	//批次按照货架顺序取
	public function my_sort($a, $b)
	{
		if ($a['ws_sort'] == $b['ws_sort']) return 0;
		return ($a['ws_sort'] < $b['ws_sort']) ? 1 : -1;
	}
	
	/**
	 * 打印订单
	 */
	public function printOrder($code,$orderCode="") {
	    $lang = Zend_Registry::get('lang');
		$productSer = new Product_Service_Product();
		$adapter = $productSer->getAdapter();
		$adapter->beginTransaction();
		//事务  保证数据从主数据库取得
		if (isset ($orderCode)&&!empty($orderCode)) {
			$this->_orderCode = $orderCode;
			$this->setOrder();
		}
		try{
			$session = new Zend_Session_Namespace('userAuth');
			$user_id=$session->userID;					//操作人
			if ($this->_order['orders_status'] != 3||$this->_order['process_status'] != 1) {			   
			    $ex = sprintf($lang['order_status_wrong'], $this->_orderCode);
				throw new Exception($ex);
			}
			if(!$this->_products){
			    $ex = sprintf($lang['order_no_product'], $this->_orderCode);
			    throw new Exception($ex);
			}
			//循环产品,按批次冻结库存
			$wpbModel = new Warehouse_Model_ProductsBatch();
			$puModel = new Warehouse_Model_ProductUseage();
			$opmModel = new Product_Model_OrderPickupMap();
			//产品总数
			$productCnt = 0;
			foreach ($this->_products as $k=>$product) {
				$sort = 0;
				$productCnt += $product['op_quantity'];
				//查询产品上架批次
				$bantchs = $wpbModel->getByCondition(array (
						"product_id" => $product['product_id'],
						"wpb_status" => 1,
						"warehouse_id"=>1 ,//默认仓库1 以后处理 待确认~~~~~~  注意注意-------------------------------------------------------
				), "*", array (
						" wpb_create_time  asc"
				));
				if(!$bantchs){
                    $ex = sprintf($lang['order_no_batch'], $this->_orderCode, $this->_order['customer_id'] . "-" . $product['product_sku'], $product['product_id']);
                    throw new Exception($ex);
                }
				foreach($bantchs as $k=>$v){
					$condition = array("ws_code"=>$v['ws_code'],'warehouse_id'=>$v['warehouse_id']);
		
					$warehouse_shelf = Warehouse_Service_Shelf::getByCondition($condition);
					if(empty($warehouse_shelf)){
					    $ex = sprintf($lang['order_ws_code_not_exists'], $this->_orderCode, $v['warehouse_id'], $v['ws_code']);
					    throw new Exception($ex);
					}
					$bantchs[$k]['ws_sort'] = $warehouse_shelf[0]['ws_sort'];
				}
				usort($bantchs, array("Order_Service_OrderProccess","my_sort"));
					
				//			print_r($product);print_r($bantchs);
				$product_bantch = array();
				$product_batch_flag = false; //批次库存是否充足
				//按批次冻结库存
				foreach ($bantchs as $bantch) {
					if($bantch['wpb_quantity']<0||$bantch['wpb_quantity_hold']<0){
					    $ex = sprintf($lang['order_product_batch_quantity_err'], $this->_orderCode, $bantch['wpb_id']);
					    throw new Exception($ex);
					}
					$sort++;
					$this->_order['ws_code'] = $bantch['ws_code'];
		
					$bantch['product_sku'] = $product['product_sku'];
					$bantch['poc_value_shortname'] = $product['category']['poc_value_shortname'];
					$bantch['product_title'] = $product['product_title'];
					$bantch['product_title_cn'] = $product['product_title_cn'];
					$bantch['pic'] = $product['pic'];
						
					if ($product['op_quantity'] > $bantch['wpb_quantity']) {
						$product_batch_flag = false;
						
						if($bantch['wpb_quantity']<=0){//库存为0，跳过 进入到下一批次
							if($bantch['wpb_quantity']==0&&$bantch['wpb_quantity_hold']==0){
								$updateRow = array (										
										"wpb_status" => 0,								
								);
								if (!$wpbModel->update($updateRow, $bantch['wpb_id'])) {
								    $ex = sprintf($lang['order_hold_quantity_fail'], $this->_orderCode);
								    throw new Exception($ex);
								}	
							}
							continue;
						}
						$updateRow = array (
								"wpb_quantity" => 0,
								"wpb_status" => 0,
								"wpb_quantity_hold" => $bantch['wpb_quantity_hold'] + $bantch['wpb_quantity'],
		
						);
						$product['op_quantity'] -= $bantch['wpb_quantity'];
						if (!$wpbModel->update($updateRow, $bantch['wpb_id'])) {
                            $ex = sprintf($lang['order_hold_quantity_fail'], $this->_orderCode);
                            throw new Exception($ex);
                        }
							
							
						$warehouse_productBatch = Warehouse_Service_ProductsBatch :: getByfield('wpb_id', $bantch['wpb_id']);
						$condition = array(
								"product_id"=>$warehouse_productBatch['product_id'],
								"ws_code"=>$warehouse_productBatch['ws_code'],
						);
						$warehouse_product = Warehouse_Service_Products :: getByCondition($condition);
						
						//状态不可用
						if($warehouse_product['wp_status']==0){
						    $ex = sprintf($lang['order_product_ws_code_unuseable'], $this->_orderCode,$warehouse_product['ws_code']);
						    throw new Exception($ex);
						}
						//产品盘点中
						if($warehouse_product['wp_status']==2){
						    $ex = sprintf($lang['order_product_pandian'], $this->_orderCode,$warehouse_product['ws_code']);
						    throw new Exception($ex);
						}
						
						//更新货架产品 数量
						$wp_quantity_hold = $warehouse_product['wp_quantity_hold'] + $bantch['wpb_quantity'];
						$wp_quantity = $warehouse_product['wp_quantity'] - $bantch['wpb_quantity'];
						if($wp_quantity<0){
						    $ex = sprintf($lang['order_product_inventory_insufficient'], $this->_orderCode,$warehouse_product['product_id']);
						    throw new Exception($ex);
						}
						$warehouse_product_row = array (
								'wp_quantity_hold' => $wp_quantity_hold,
								'wp_quantity' => $wp_quantity,
						);
						Warehouse_Service_Products::update($warehouse_product_row,$warehouse_product['wp_id']);
		
						//货架使用日志
						$WarehouseProductsLog = array(
								'wpl_refId' => $this->_orderCode,
								'user_id' => $user_id,
								'warehouse_id' => $warehouse_product['warehouse_id'],
								'ws_code' => $warehouse_product['ws_code'],
								'wpl_proc_type' => 4, //状态修改
								'wpl_note' => '下架更改货架库存，冻结库存由'.$warehouse_product['wp_quantity_hold'].'变为'.$wp_quantity_hold."可用库存由".$warehouse_product['wp_quantity']."变为".$wp_quantity,
						);
						if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
						    $ex = sprintf($lang['order_product_log_fail'], $this->_orderCode);
						    throw new Exception($ex);
		
						}
		
						//记录order pickup map
						$mapRow = array (
								"op_code" => $code,
								"orders_code" => $this->_order['orders_code'],
								"opm_sort" => $sort,
								"product_id" => $product['product_id'],
								"opm_quantity" => $bantch['wpb_quantity'],
								"wpb_id" => $bantch['wpb_id'],
								"ws_code" => $bantch['ws_code'],
								"opm_create_date" => date("Y-m-d H:i:s"),
		
		
						);
						//从该批次拿的数量
						$bantch['take'] = $bantch['wpb_quantity'];
						// 					$product_bantch[] = $bantch;
						// 					if(isset($this->_order['product_bantch'][$bantch['ws_code']."__".$bantch['warehouse_id']])){
						// 						$this->_order['product_bantch'][$bantch['ws_code']."__".$bantch['warehouse_id']]['take'] += $bantch['take'];
						// 					}else{
						// 						$this->_order['product_bantch'][$bantch['ws_code']."__".$bantch['warehouse_id']] = $bantch;
						// 					}
							
						$this->_order['product_bantch'][$bantch['ws_code']."__".$bantch['wpb_id']] = $bantch;
							
							
						if (!$opmModel->create($mapRow)) {
						    $ex = sprintf($lang['order_op_fail'], $this->_orderCode);
						    throw new Exception($ex);
						}
						// 					//记录product usage
						$log = "订单配货，冻结库存,可用数from ".$bantch['wpb_quantity']."to ".$updateRow['wpb_quantity'].",冻结数from ".$bantch['wpb_quantity_hold']."to ".$updateRow['wpb_quantity_hold'];
						$this->createUsage($bantch['wpb_id'],2,$bantch['wpb_quantity'],$bantch['wpb_quantity'],$log);
						// 					$row = array (
						// 						"wpu_type" => 1,
						// 						"wpu_proc_type" => 2,
						// 						"wpu_refId" => $this->_order["orders_code"],
						// 						"wpu_quantity" => $bantch['wpb_quantity'],
						// 						"wpu_current_qty" => 0,
						// 						"wpu_note" => "订单配货",
						// 						"wpb_id" => $bantch['wpb_id'],
// 						"ws_code" => $bantch['ws_code'],
						// 						"wpu_create_time" => date("Y-m-d H:i:s"),
		
						// 					);
						// 					if (!$puModel->create($row)) {
						// 						throw new Exception("订单：".$this->_orderCode." 记录库存冻结失败");
						// 					}
					} else {
						$product_batch_flag = true;
						$updateRow = array (
								"wpb_quantity" => $bantch['wpb_quantity'] - $product['op_quantity'],
								"wpb_quantity_hold" => $bantch['wpb_quantity_hold'] + $product['op_quantity'],
		
		
						);
						if ($bantch['wpb_quantity'] == $product['op_quantity'])
							$updateRow['wpb_status'] = 0;
						if (!$wpbModel->update($updateRow, $bantch['wpb_id'])) {
						    $ex = sprintf($lang['order_op_fail'], $this->_orderCode);
						    throw new Exception($ex);
						}
							
							
						$warehouse_productBatch = Warehouse_Service_ProductsBatch :: getByfield('wpb_id', $bantch['wpb_id']);
						$condition = array(
								"product_id"=>$warehouse_productBatch['product_id'],
								"ws_code"=>$warehouse_productBatch['ws_code'],
						);
						$warehouse_product = Warehouse_Service_Products :: getByCondition($condition);
							
					    //状态不可用
						if($warehouse_product['wp_status']==0){
						    $ex = sprintf($lang['order_product_ws_code_unuseable'], $this->_orderCode,$warehouse_product['ws_code']);
						    throw new Exception($ex);
						}
						//产品盘点中
						if($warehouse_product['wp_status']==2){
						    $ex = sprintf($lang['order_product_pandian'], $this->_orderCode,$warehouse_product['ws_code']);
						    throw new Exception($ex);
						}
							
						$wp_quantity_hold = $warehouse_product['wp_quantity_hold'] + $product['op_quantity'];
						$wp_quantity = $warehouse_product['wp_quantity'] - $product['op_quantity'];
						if($wp_quantity<0){
						    $ex = sprintf($lang['order_product_batch_quantity_err'], $this->_orderCode, $bantch['wpb_id']);
						    throw new Exception($ex);
						}
						//更新货架产品 数量
						$warehouse_product_row = array (
								'wp_quantity_hold' => $wp_quantity_hold,
								'wp_quantity' => $wp_quantity,
						);
						Warehouse_Service_Products::update($warehouse_product_row,$warehouse_product['wp_id']);
						//货架使用日志
						$WarehouseProductsLog = array(
								'wpl_refId' => $this->_orderCode,
								'user_id' => $user_id,
								'warehouse_id' => $warehouse_product['warehouse_id'],
								'ws_code' => $warehouse_product['ws_code'],
								'wpl_proc_type' => 4, //状态修改
								'wpl_note' => '下架更改货架库存，冻结库存由'.$warehouse_product['wp_quantity_hold'].'变为'.$wp_quantity_hold."可用库存由".$warehouse_product['wp_quantity']."变为".$wp_quantity,
						);
						if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
                            $ex = sprintf($lang['order_op_fail'], $this->_orderCode);
							throw new Exception($ex);
						}
		
		
						//记录order pickup map
						$mapRow = array (
								"op_code" => $code,
								"orders_code" => $this->_order['orders_code'],
								"opm_sort" => $sort,
								"product_id" => $product['product_id'],
								//						"opm_quantity" => $updateRow['wpb_quantity'],//bug 改为以下
								"opm_quantity" => $product['op_quantity'],
								"wpb_id" => $bantch['wpb_id'],
								"ws_code" => $bantch['ws_code'],
								"opm_create_date" => date("Y-m-d H:i:s"),
						);
						//从该批次拿的数量
						$bantch['take'] = $product['op_quantity'];
						$product_bantch[] = $bantch;
							
						// 					if(isset($this->_order['product_bantch'][$bantch['ws_code']."__".$bantch['warehouse_id']])){
						// 						$this->_order['product_bantch'][$bantch['ws_code']."__".$bantch['warehouse_id']]['take'] += $bantch['take'];
						// 					}else{
						// 						$this->_order['product_bantch'][$bantch['ws_code']."__".$bantch['warehouse_id']] = $bantch;
						// 					}
						$this->_order['product_bantch'][$bantch['ws_code']."__".$bantch['wpb_id']] = $bantch;
							
						if (!$opmModel->create($mapRow)) {							
						    $ex = sprintf($lang['order_op_fail'], $this->_orderCode);
						    throw new Exception($ex);
						}
						//记录product usage
						$log = "订单配货，冻结库存,可用数from ".$bantch['wpb_quantity']."to ".$updateRow['wpb_quantity'].",冻结数from ".$bantch['wpb_quantity_hold']."to ".$updateRow['wpb_quantity_hold'];
		
						$this->createUsage($bantch['wpb_id'],2,$bantch['wpb_quantity'],$product['op_quantity'],$log);
						// 					$row = array (
						// 						"wpu_type" => 1,
						// 						"wpu_proc_type" => 2,
						// 						"wpu_refId" => $this->_order["orders_code"],
						// 						"wpu_quantity" => $product['op_quantity'],
						// 						"wpu_current_qty" => $updateRow['wpb_quantity'],
						// 						"wpu_note" => "订单配货",
						// 						"wpb_id" => $bantch['wpb_id'],
// 						"ws_code" => $bantch['ws_code'],
						// 						"wpu_create_time" => date("Y-m-d H:i:s"),
		
		
						// 					);
						// 					if (!$puModel->create($row)) {
						// 						throw new Exception("订单：".$this->_orderCode." 记录库存冻结失败");
						// 					}
						break;
					}
				}
					
				if (!$product_batch_flag) {
				    $ex = sprintf($lang['order_product_inventory_insufficient'], $this->_orderCode,$product['product_id']);
				    throw new Exception($ex);
				}
				if(empty($product_bantch)){
					$product_bantch[] = array("ws_code"=>"","take"=>'Inner Error');
				}
				$this->_products[$k]['bantch'] = $product_bantch;
			}
			//更新产品状态
			$ordeUpdateRow = array (
					//"orders_status" => 4,
					"process_status" => 2,
						
			);
			$obj = new Order_Model_Order();
		
			$obj->update($ordeUpdateRow, $this->_order['order_id']);
		
			$this->createOrderLog("process_status 1 to 2");
		
		
			$this->_order['productCnt'] = $productCnt;
			$this->_order['order_product'] = $this->_products;
			
			//更新订单打印时间
			$orderRow = array(
					"print_time" => date("Y-m-d H:i:s"),
			);
			Order_Service_Order::update($orderRow,$this->_order['order_id']);//更新订单打印时间
			
			$adapter->commit();
		}catch(Exception $e){
			$adapter->rollback();
			$this->_order['err']= $e->getMessage();			
		}
		return $this->_order;
	}

	/*
	*
	*获取客户LOGIN信息
	*
	*/
	private function setCustomer() {
		$this->_customerId = $this->_order['customer_id'];
		$this->_customer = Customer_Service_Customer :: getByCustomerId($this->_customerId);
	}

	private function setOrder() {
		if (!isset ($this->_order) || $this->_order['orders_code'] == $this->_orderCode) {
			$this->_order = current(Order_Service_Order :: getByfield('orders_code', $this->_orderCode));
			$order_refer_info_Model = new Order_Model_OrderReferInfo();
			$ORIobj=$order_refer_info_Model->getByOrdersCode($this->_orderCode);
			if(!empty($ORIobj)){
				$this->_order['order_refer_info'] = $ORIobj->toArray();
			}
			$condition['orders_code'] = $this->_orderCode;
			$this->_products = Order_Service_Product :: getByCondition($condition);
			$productSer = new Product_Service_Product();
			$this->_order['pp_name'] = "";
			foreach ($this->_products as $key => $value) {
				$this->_products[$key]["category"] = $productSer->getProductCategory($value['product_id']);
				$product = $productSer->getByProductId($value['product_id']);
				if($product){
					$this->_products[$key]["product_title"] =  empty($product['product_title_cn'])?$product['product_title']:$product['product_title_cn'];	
					$this->_products[$key]["product_title_cn"] =  $product['product_title_cn'];	
					$this->_products[$key]["product_sku"] =  $product['product_sku'];
					$this->_products[$key]["pic"] =  "/product/product/view-picture/id/" . ($value["product_id"]);	
					//包材
					if(empty($this->_order['pp_name'])){
						$row_PackageMap = Product_Service_PackageMap::getAllByProductId ( $value ['product_id'] );
					
						if($row_PackageMap){
							$row_package = Product_Service_Package::getByPpid ( $row_PackageMap ['package_id'] );
							$this->_products[$key]['pp_name'] = $row_package['pp_name'];
							$this->_order['pp_name'] = $row_package['pp_name'];
						}
					}
					
// // 					产品缩略图
// 					$attach = Product_Service_Attached::getProductPicture($value['product_id']);	
					
// 					if($attach){
// 						if($attach['pa_file_type'] == "img"){
// 							$this->_products[$key]["pic"] =  "/product/product/view-img/customer_id/".$product['customer_id']."/product_id/".$product['product_id']."/pa_path/".$attach['pa_path']."/";
// 						}else{
// 							$this->_products[$key]["pic"] =  $attach['pa_path'];
// 						}
// 					}else{
// 						$this->_products[$key]["pic"] =  "/image/noimg.jpg";
// 					}
									

					
				}
				
				 
			}
			$this->_order['order_product'] = $this->_products;	//为什么注释掉？
		}
	}
	/*
	*
	*Return Order Info
	*/
	public function getOrder() {
		return $this->_order;
	}
	/*
	 * 更改订单状态
	 * 
	 */
	public function changeStatus($row) {
	    $lang = Zend_Registry::get('lang');
		$obj = new Order_Model_Order();
		if(!$obj->update($row, $this->_order['order_id'])){
			throw new Exception($this->_order['orders_code']."".$lang['order_change_status_fail']);
		}
	}
	/*
	 * 退回预扣费用
	 * 
	 */
	public function feeBack() {
	    $lang = Zend_Registry::get('lang');
		$note = 'back shipping fee '.$this->_order['shipping_fee_estimate'].'. Order:'.$this->_order['orders_code'];
		$options = array('cbhClass'=>2,	//正常退款
						 'refCode'=>$this->_order['orders_code'],
						 'appType'=>4,	//物流费用回退
						 'cbhType'=>'1',
						 'vale'=>$this->_order['shipping_fee_estimate'],
						 'currencyCode'=>"RMB",
						 'note'=>$note
						);
						
		if(!Customer_Service_CustomerBalance::procBalance($this->_order['customer_id'],$options)){
			throw new Exception($this->_order['orders_code']."".$lang['order_back_fee_fail']);
// 			return;
		}
	}

	/*
	 * 更新总冻结可用库存
	 * 
	 */
	public function productStocketBack() {
		
		//获取订单产品
		$order_products = Order_Service_Product :: getByfield("orders_code", $this->_order['orders_code']);
		foreach ($order_products as $op) {
			$warehouseId = 1;
			$product_stocket = Product_Service_ProductStocket :: getByProductId($op['product_id'],$warehouseId);

			$row_product_stocket = array (
				"ps_quantity" => ($product_stocket['ps_quantity'] + $op['op_quantity']),
				"ps_quantity_hold" => ($product_stocket['ps_quantity_hold'] - $op['op_quantity']),
				
			);
			
			
//			print_r($warehouse_product);
			if(!Product_Service_ProductStocket :: update($row_product_stocket, $product_stocket['product_id'],$warehouseId)){
				throw new Exception($this->_order['orders_code']."更新总冻结可用库存(product_id:".$product_stocket['product_id'].")失败");
// 				break;
			}
			
		}
//		exit;
	}
	
	
	/*
	 * 
	 * 更新冻结批次可用库存
	 * 
	 */
	public function wareHouseProductBatchBack() {
		
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;					//操作人
		//出货单
		$model_orderPickupMap = new Order_Model_OrderPickupMap();
		$orderPickupMaps = $model_orderPickupMap->getByfield("orders_code", $this->_order['orders_code']);

		foreach ($orderPickupMaps as $opm) {
			$warehouse_productBatch = Warehouse_Service_ProductsBatch :: getByfield('wpb_id', $opm['wpb_id']);
			$warehouse_productBatch_row = array (
				'wpb_quantity_hold' => $warehouse_productBatch['wpb_quantity_hold'] - $opm['opm_quantity'],
				'wpb_quantity' => $warehouse_productBatch['wpb_quantity'] + $opm['opm_quantity'],
				'wpb_status'=>1				
			);
			
			if($warehouse_productBatch['product_id']!=$opm['product_id']){				
				throw new Exception($this->_order['orders_code']."货架:".$warehouse_productBatch['ws_code']." 货架产品与回退产品不一致1");
			}
			
			//更新批次库存
			if(!Warehouse_Service_ProductsBatch :: update($warehouse_productBatch_row, $opm['wpb_id'])){
				throw new Exception($this->_order['orders_code']."更新批次库存(wpb_id:".$opm['wpb_id'].")失败");
// 				break;
			}
			$log = "订单回退,冻结库存-,可用库存+,可用数from ".$warehouse_productBatch['wpb_quantity']."to ".$warehouse_productBatch_row['wpb_quantity'].
					",冻结数from ".$warehouse_productBatch['wpb_quantity_hold']."to ".$warehouse_productBatch_row['wpb_quantity_hold'];
				
			$this->createUsage($opm['wpb_id'],2,($warehouse_productBatch['wpb_quantity'] + $warehouse_productBatch['wpb_quantity_hold']),$opm['opm_quantity'],$log);
			
			$condition = array(
				"product_id"=>$warehouse_productBatch['product_id'],
				"ws_code"=>$warehouse_productBatch['ws_code'],
			);
			$warehouse_product = Warehouse_Service_Products :: getByCondition($condition);
			//更新货架产品 数量
			$warehouse_product_row = array (
				'wp_quantity_hold' => $warehouse_product['wp_quantity_hold'] - $opm['opm_quantity'],
				'wp_quantity' => $warehouse_product['wp_quantity'] + $opm['opm_quantity'],
				'wp_status' => 1,
			);
			if(!Warehouse_Service_Products::update($warehouse_product_row,$warehouse_product['wp_id'])){
				throw new Exception($this->_order['orders_code']."更新货架产品(ws_code:".$warehouse_productBatch['ws_code']." wp_id:".$warehouse_product['wp_id'].") 数量失败");
// 				break;
			}
			
			
			$wp_quantity_hold = $warehouse_product['wp_quantity_hold'] - $opm['opm_quantity'];
			$wp_quantity = $warehouse_product['wp_quantity'] + $opm['opm_quantity'];
			//货架使用日志
			$WarehouseProductsLog = array(
					'wpl_refId' => $this->_orderCode,
					'user_id' => $user_id,
					'warehouse_id' => $warehouse_product['warehouse_id'],
					'ws_code' => $warehouse_product['ws_code'],
					'wpl_proc_type' => 4, //状态修改
					'wpl_note' => '订单由下架中变为待下架，回退冻结库存和可用库存，冻结库存由'.$warehouse_product['wp_quantity_hold'].'变为'.$wp_quantity_hold."可用库存由".$warehouse_product['wp_quantity']."变为".$wp_quantity,
			);
			if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
				throw new Exception("订单货架写入使用日志失败失败：".$this->_orderCode." --> ".$warehouse_product['ws_code']." ");
					
			}
			

		}

	}
	/*
	 * 
	 * 更新冻结批次可用库存+出货量
	 * 
	 */
	public function wareHouseProductBatchHoldBack() {
		
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;					//操作人
		//出货单
		$model_orderPickupMap = new Order_Model_OrderPickupMap();
		$orderPickupMaps = $model_orderPickupMap->getByfield("orders_code", $this->_order['orders_code']);

		foreach ($orderPickupMaps as $opm) {
			$warehouse_productBatch = Warehouse_Service_ProductsBatch :: getByfield('wpb_id', $opm['wpb_id']);
			$warehouse_productBatch_row = array (
				'wpb_quantity_hold' => $warehouse_productBatch['wpb_quantity_hold'] + $opm['opm_quantity'],				
				'wpb_status'=>1				
			);
			
			if($warehouse_productBatch['product_id']!=$opm['product_id']){
				throw new Exception($this->_order['orders_code']."货架:".$warehouse_productBatch['ws_code']." 货架产品与回退产品不一致2");
			}
			//更新批次库存
			if(!Warehouse_Service_ProductsBatch :: update($warehouse_productBatch_row, $opm['wpb_id'])){
				throw new Exception($this->_order['orders_code']."更新批次库存(wpb_id:".$opm['wpb_id'].")失败");
				//break;
			}
			$log = "订单回退,冻结库存+,可用库存 ".$warehouse_productBatch['wpb_quantity'].",冻结数from ".$warehouse_productBatch['wpb_quantity_hold']."to ".$warehouse_productBatch_row['wpb_quantity_hold'];
			$this->createUsage($opm['wpb_id'],2,($warehouse_productBatch['wpb_quantity']+$warehouse_productBatch['wpb_quantity_hold'] ),$opm['opm_quantity'],$log);
				
			$condition = array(
				"product_id"=>$warehouse_productBatch['product_id'],
				"ws_code"=>$warehouse_productBatch['ws_code'],
			);
			$warehouse_product = Warehouse_Service_Products :: getByCondition($condition);
			//更新货架产品 数量
			$warehouse_product_row = array (
				'wp_quantity_hold' => $warehouse_product['wp_quantity_hold'] + $opm['opm_quantity'],
				'wp_status' => 1,
			);
			if(!Warehouse_Service_Products::update($warehouse_product_row,$warehouse_product['wp_id'])){
				throw new Exception($this->_order['orders_code']."更新货架产品 数量(ws_code:".$warehouse_productBatch['ws_code']." wp_id:".$warehouse_product['wp_id'].")失败".$warehouse_productBatch['product_id']."__".$warehouse_productBatch['ws_code']);
				//break;
			}
			
			$wp_quantity_hold = $warehouse_product['wp_quantity_hold'] + $opm['opm_quantity'];
			//货架使用日志
			$WarehouseProductsLog = array(
					'wpl_refId' => $this->_orderCode,
					'user_id' => $user_id,
					'warehouse_id' => $warehouse_product['warehouse_id'],
					'ws_code' => $warehouse_product['ws_code'],
					'wpl_proc_type' => 4, //状态修改
					'wpl_note' => '订单由下架确认变为下架中，回退冻结库存，更改货架库存，冻结库存由'.$warehouse_product['wp_quantity_hold'].'变为'.$wp_quantity_hold."可用库存为".$warehouse_product['wp_quantity'],
			);
			
			
			if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
				throw new Exception("订单：".$this->_orderCode." 货架 ".$warehouse_product['ws_code']." 写入使用日志失败失败");
					
			}
			
			
		}

	}

	/*
	 * 
	 * 清除下架明细
	 * 
	 * 
	 */
	public function clearOrderPickupMap() {
		
		$model_orderPickupMap = new Order_Model_OrderPickupMap();
		//下架单
		$pickUp = $model_orderPickupMap->getByOrdersCode($this->_order['orders_code']);		
		
		if(!$model_orderPickupMap->deleteByOrderCode($this->_order['orders_code'])){
			throw new Exception($this->_order['orders_code']."清除下架明细失败");
		}
		//当下架明细中无该下架单的记录，删除之		
		if(!$model_orderPickupMap->getByfield("op_code",$pickUp['op_code'])->toArray()){
			$opModel = new Product_Model_OrderPickup();	
			if(!$opModel->deleteByOpCode($pickUp['op_code'])){
				throw new Exception($this->_order['orders_code']."清除配货单失败");
			}
		}
		

	}
	/*
	 * 
	 * 删除订单运输信息
	 * 
	 * 
	 */
	public function clearOrderShip() {
		$orderShip = new Order_Model_OrderShip();
        //将之前的数据更新状态为0，
		if(!$orderShip->updateByOrdersCodeAndOsid(array('os_status'=>0),$this->_order['orders_code'],0)){
// 			throw new Exception($this->_order['orders_code']."更新订单运输信息失败!orderShip");
		}
		
	}
	


	/*
	 * 
	 * 订单删除
	 * 
	 */
	public function delete() {
		$obj = new Order_Model_Order();

		$dbAdapter = $obj->getAdapter();
		$dbAdapter->beginTransaction();
		try {
			switch ($this->_order['process_status']) {
				//orders_status   状态( 0删除,1,草稿，2已确认，3,已提交 4,On Hold，，5,已发货,6已签收),
				//process_status  状态(0:未提交,1:待下架, 2:下架中, 3:已下架, 4:待发货, 5:已发货,6:完成)			
				case 1 :
					//订单退回删除状态，退回预扣的费用 退回总冻结的可用库存					
					
					//订单退回删除
					$row_order = array (
						"orders_status" => 0,
						"process_status" => 0,
						"import_status"=>0,
						"print_time" => 0,
					);
					$this->changeStatus($row_order);
				
					//退回预扣费用
					$this->feeBack();
					//更新总冻结可用库存
					$this->productStocketBack();

					
					//删除订单运输信息
					$this->clearOrderShip();
					
	  				$this->createOrderLog("process_status ".$this->_order['process_status']." to 0");
	
					break;
				case 2 :
					//下架中状态的订单删除，订单退回已提交状态，要清除相应的下架明细，以及被冻结的批次库存				
					
						$row_order = array (
							"process_status" => 1,
							"print_time" => 0,
						);
						$this->changeStatus($row_order);
	
						//更新批次库存
						$this->wareHouseProductBatchBack();
	
						//清除下架明细
						$this->clearOrderPickupMap();
						//删除订单运输信息
	// 					$this->clearOrderShip();
	  					$this->createOrderLog("process_status ".$this->_order['process_status']." to 1");
					break;
				case 3 :
					//已下架状态的订单删除，订单退回已提交状态，同样要清除相应的下架明细，以及被冻结的批次库存
				
						//订单退回提交状态
						$row_order = array (
							"process_status" => 1,
							"print_time" => 0,
						);
						$this->changeStatus($row_order);
						
						//更新批次库存:批次冻结库存=批次冻结库存+出货量	
						$this->wareHouseProductBatchHoldBack();
						
						//更新批次库存	
						$this->wareHouseProductBatchBack();
	
						
						//清除下架明细
						$this->clearOrderPickupMap();

						
						//删除订单运输信息
 						$this->clearOrderShip();
						
	  					$this->createOrderLog("process_status ".$this->_order['process_status']." to 1");
	
					break;
				case 4 :
					//打包后的订单删除，订单退回已提交状态，要清除相应的下架明细，以及被冻结的批次库存，还要清除订单物流表相关的记录(代发货)
					
						//订单退回提交状态
						$row_order = array (
							"process_status" => 1,
							"print_time" => 0,
						);
						$this->changeStatus($row_order);
						
						//更新批次库存:批次冻结库存=批次冻结库存+出货量	
						$this->wareHouseProductBatchHoldBack();
						
						//更新批次库存	
						$this->wareHouseProductBatchBack();
	
						//清除下架明细
						$this->clearOrderPickupMap();

						//删除订单运输信息
 						$this->clearOrderShip();
						
	  					$this->createOrderLog("process_status ".$this->_order['process_status']." to 1");
						
	
					break;
				default :
					break;
	
			}		
			
			
		} catch (Exception $e) {
			$dbAdapter->rollback();
			return array("ask"=>0,"msg"=>$e->getMessage());
		}		
		$dbAdapter->commit();
		
		return array("ask"=>1,"msg"=>"操作成功");
	}
	
	
	//截单
	/*
	 *
	* 订单删除
	*
	*/
	public function stop() {
		$obj = new Order_Model_Order();
	
		$dbAdapter = $obj->getAdapter();
		$dbAdapter->beginTransaction();
		
		try {
			switch ($this->_order['process_status']) {
				//orders_status   状态( 0删除,1,草稿，2已确认，3,已提交 4,On Hold，，5,已发货,6已签收),
				//process_status  状态(0:未提交,1:待下架, 2:下架中, 3:已下架, 4:待发货, 5:已发货,6:完成)
				case 1 :
					//订单退回删除状态，退回预扣的费用 退回总冻结的可用库存
						
					//订单退回删除
					$row_order = array (
					"orders_status" => 0,
					"process_status" => 0,
					"import_status"=>0,
					"print_time" => 0,
					);
					$this->changeStatus($row_order);
	
					//退回预扣费用
					$this->feeBack();
					//更新总冻结可用库存
					$this->productStocketBack();

						
					$this->createOrderLog("process_status ".$this->_order['process_status']." to 0");
	
					break;
				case 2 :
					//下架中状态的订单删除，订单退回已提交状态，要清除相应的下架明细，以及被冻结的批次库存
						
					$row_order = array (
					"process_status" => 1,
					"print_time" => 0,
					);
					$this->changeStatus($row_order);
	
					//更新批次库存
					$this->wareHouseProductBatchBack();
	
					//清除下架明细
					$this->clearOrderPickupMap();

					$this->createOrderLog("process_status ".$this->_order['process_status']." to 1");
					break;
				case 3 :
					//已下架状态的订单删除，订单退回已提交状态，同样要清除相应的下架明细，以及被冻结的批次库存
	
					//订单退回提交状态
					$row_order = array (
					"process_status" => 1,
					"print_time" => 0,
					);
					$this->changeStatus($row_order);
	
					//更新批次库存:批次冻结库存=批次冻结库存+出货量
					$this->wareHouseProductBatchHoldBack();
	
					//更新批次库存
					$this->wareHouseProductBatchBack();
	
	
					//清除下架明细
					$this->clearOrderPickupMap();


					$this->createOrderLog("process_status ".$this->_order['process_status']." to 1");
	
					break;
				case 4 :
					//打包后的订单删除，订单退回已提交状态，要清除相应的下架明细，以及被冻结的批次库存，还要清除订单物流表相关的记录(代发货)
						
					//订单退回提交状态
					$row_order = array (
					"process_status" => 1,
					"print_time" => 0,
					);
					$this->changeStatus($row_order);
	
					//更新批次库存:批次冻结库存=批次冻结库存+出货量
					$this->wareHouseProductBatchHoldBack();
	
					//更新批次库存
					$this->wareHouseProductBatchBack();
	
					//清除下架明细
					$this->clearOrderPickupMap();

					$this->createOrderLog("process_status ".$this->_order['process_status']." to 1");
	
	
					break;
				default :
					break;
	
			}
				
			//截单确认
			if($this->_order['underreview_status']==3&&$this->_order['orders_status']>0&&$this->_order['process_status']>0){
				
				$date=date("Y-m-d:H:i:s");
				//订单退回删除
				$row_order = array (
						"orders_status" => 0,
						"process_status" => 0,
						"last_modified_time"=>$date,
						"print_time" => 0,
				);

				$this->changeStatus($row_order);
					
				//退回预扣费用
				$this->feeBack();
				//更新总冻结可用库存
				$this->productStocketBack();
                //删除订单运输信息
                $this->clearOrderShip();
					
				$this->createOrderLog("process_status ".$this->_order['process_status']." to 0");
			}
		} catch (Exception $e) {
			
			$dbAdapter->rollback();
			return array("ask"=>0,"msg"=>$e->getMessage());
		}
		
		$dbAdapter->commit();
	
		return array("ask"=>1,"msg"=>"操作成功");
	}
	
	
	
	public static function  htmlParser($html){
		preg_match_all('//',$html,$ms);	
	}
	
	/*
	 * 
	 * 重新提交异常订单
	 * 
	 * 
	 */
	public static function orderResubmit() {
		$condition = array("orders_status"=>4,"underreview_status"=>1);
		$orders = Order_Service_Order::getByCondition($condition);
		$result = array();
		foreach($orders as $order){
			$obj = new Order_Service_OrderReProccess($order['orders_code']);
			$arr =  $obj->submited($order['orders_code'],3);			
			$result[] = $arr;				
		}
		
		return $result;
	}
	
	
	public  function createOrderLog($remark='',$status=3){
		$session = new Zend_Session_Namespace('userAuth');
        $userid=isset($session->userID)?$session->userID:0;
		$logRow = array (
			"orders_code" => $this->_orderCode,
			"osh_type" => "Process",
			"osh_statu" => $status,
			"osh_create_date" => date("Y-m-d H:i:s"),
			"osh_comments" => "order status Process",
			"osh_remark" => $remark,
			"user_id" => $userid,
			"osh_ip" => $_SERVER['REMOTE_ADDR'],
		);
		$model = new Order_Model_History();
		$model->create($logRow);
		 
	}
	//验证订单产品与配货产品是否一致，包括产品数和产品名称
	public static function validatePickupMap($ordersCode){
		$orderProduct = Order_Service_Product::getByfield("orders_code", $ordersCode);
		$orderPickupMap = Product_Service_OrderPickupMap::groupByProductId($ordersCode);	
		$result = array("ask"=>1);
			
		$orderProduct_clone = array();
		foreach($orderProduct as $v){
			$orderProduct_clone[$v['product_id']] = $v;
		}
		$orderPickupMap_clone = array();
		foreach($orderPickupMap as $v){			
			$orderPickupMap_clone[$v['product_id']] = $v;
		}
		if(count($orderProduct_clone)!=count($orderPickupMap_clone)){
			$result['ask'] = 0;
			$result['msg'] = "订单配货产品与订单产品不一致,订单产品ID:".implode(",", array_keys($orderProduct_clone)).
							 "配货产品ID：".implode(",", array_keys($orderPickupMap_clone));
			return $result;
		}
		foreach($orderProduct_clone as $k=>$v){
			if(!isset($orderPickupMap_clone[$k])){
				$result['ask'] = 0;
				$result['msg'] = "订单配货产品与订单产品不一致,订单产品ID:".implode(",", array_keys($orderProduct_clone)).
							 	 "配货产品ID：".implode(",", array_keys($orderPickupMap_clone));			
				break;
			}
			if($v['op_quantity']!=$orderPickupMap_clone[$k]['opm_quantity']){
				$result['ask'] = 0;
				$result['msg'] = "订单配货产品数量与订单产品数量不一致，产品ID：".$v['product_id'].
								 ",订单数量为：".$v['op_quantity']." 配货数量为：".$orderPickupMap_clone[$k]['opm_quantity'];
				break;
			}
		}
		return $result;
		
	}

    //判断申报价值
    private  function getDeclaredValue(){
        //申报价值用全价
        $shippingMethod=array('RM1','RM1R','EUEXP','SWBAM','SWBRAN');
        if(isset($this->_order['shipping_method']) && !in_array($this->_order['shipping_method'],$shippingMethod)){
            $this->_rule = 2;
        }

        //设置订单行申报价值总价=订单申报价值
        $minValue = 20 ;
        if(in_array(strtoupper($this->_order['shipping_method']),array('TWDHL','CNDHL')) && $this->_order['parcel_declared_value'] <= $minValue  ){
            $this->_order['parcel_declared_value'] = $minValue;
            $opDeclaredValue=round($minValue/count($this->_products),2) * $this->_rule ; //考虑到有此运输方式是除于2
            foreach($this->_products as $key => $value){
                 $this->_products[$key]['op_declared_value'] = $opDeclaredValue ;
            }
        }
    }
	
	//2012年6月6日16:21:08 打包贴标
	public static function packageAndLabel($ordersCode){
		$response = array("ask"=>0);
		$s = new Order_Service_Order();
		$obj = new Order_Model_Order();		
		$dbAdapter = $obj->getAdapter();
		$dbAdapter->beginTransaction();
		try{
			$s = new Order_Service_Order();
			$order=$s->getByOrdersCode($ordersCode);
			if(!$order){
				throw new Exception ( "订单{$ordersCode}不存在" );
			}
			if($order['orders_status']!=3||!in_array($order['process_status'],array(2,3))){
				throw new Exception ( "订单{$ordersCode}状态不正确,当前状态为".$order['orders_status'].",".$order['process_status'] );
			}
			//订单未下架
			if($order['process_status']==2){
				//订单下架
				$result = self::confirmPickup($ordersCode);	
				//日志
				self::createOrderLogNew($ordersCode, $order['orders_status'], $order['process_status'], 3, 3,"订单下架");
			}
			//取消未下架订单的打包贴标功能 2012年7月5日
// 			if($order['orders_status']!=3||!in_array($order['process_status'],array(3))){
// 				throw new Exception ( "订单{$ordersCode}状态不正确,当前状态为".$order['orders_status'].",".$order['process_status'] );
// 			}
			
			$order_row = array();
			$order_row ['process_status'] = 4;
			if(!Order_Service_Order::update ( $order_row, $order ['order_id'] )){
				throw new Exception ( "更新订单{$ordersCode}状态失败" );
			}
			
			//日志
			self::createOrderLogNew($ordersCode, 3, 3, 3, 4,"打包贴标");
			$dbAdapter->commit();
		}catch (Exception $e){	
			$dbAdapter->rollback();
			Zend_Registry::get('log')->info($e->getMessage());
// 			$response['msg'] = $e->getMessage();
			$response['msg'] = $lang['order_operation_fail'];
			return $response;
		}
		$response['ask'] = 1;
		return $response;
	}
	
	/**
	 *确认下架
	 @param pickupCode=>配货单单号
	 @return boolean
	 */
	protected  static function confirmPickup($ordersCode){
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=isset($session->userID)?$session->userID:0;
		
		$customerBalance = new Customer_Model_CustomerBalance();

		$date=date("Y-m-d:H:i:s");
		
		$PickupMapmodel = new Product_Model_OrderPickupMap();
		$pickupmodel = new Product_Model_OrderPickup();
		$ordermodel = new Order_Model_Order();

		$condition=array(
				'orders_code'=>$ordersCode,
		);
		$pickupmapRows = $PickupMapmodel->getByCondition($condition,'*');
		if(empty($pickupmapRows)){
			throw new Exception("数据异常，订单 ".$ordersCode." 无订单产品！！");
		}
		
		$order = Order_Service_Order::getByOrdersCode($ordersCode);
		foreach($pickupmapRows as $key => $val){
			$ProBrow=Warehouse_Service_ProductsBatch::getById($val['wpb_id']);

			$current_quantity=$ProBrow['wpb_quantity']+$ProBrow['wpb_quantity_hold']-$val['opm_quantity'];
			$current_quantity_hold=$ProBrow['wpb_quantity_hold']-$val['opm_quantity'];
			$updateRow=array(
					'wpb_quantity_hold'=>$current_quantity_hold,
					'wpb_status'=>	$current_quantity<0||$current_quantity_hold<0||($current_quantity==0&&$current_quantity_hold==0)?0:1,
			);
			if($updateRow['wpb_quantity_hold']<0||$ProBrow['wpb_quantity']<0){
				throw new Exception("数据异常，批次 ".$ProBrow['wpb_id']." 可用数量或冻结数量小于0");
			}
			if(Warehouse_Service_ProductsBatch::update($updateRow,$val['wpb_id'])){

				if($order['orders_status']!=3 || $order['process_status']!=2){
					throw new Exception ( "订单{$ordersCode}状态不正确,当前状态为".$order['orders_status'].",".$order['process_status'] );
				}
					
				$warehouse_productBatch = Warehouse_Service_ProductsBatch :: getByfield('wpb_id', $val['wpb_id']);
				$condition = array(
						"product_id"=>$warehouse_productBatch['product_id'],
						"ws_code"=>$warehouse_productBatch['ws_code'],
						"warehouse_id"=>$warehouse_productBatch['warehouse_id'],
				);
				$warehouse_product = Warehouse_Service_Products :: getByCondition($condition);
				//状态不可用
				if($warehouse_product['wp_status']==0){
					throw new Exception("订单：".$val['orders_code']." 产品Id：".$warehouse_product['product_id']." 货架".$warehouse_product['ws_code']."不可用");
				}
				//产品盘点中
				if($warehouse_product['wp_status']==2){
					throw new Exception("订单：".$val['orders_code']." 产品Id：".$warehouse_product['product_id']." 货架".$warehouse_product['ws_code']."库存盘点");
				}
				
				$wp_quantity_hold = $warehouse_product['wp_quantity_hold'] - $val['opm_quantity'];
				//更新货架产品 数量
				$warehouse_product_row = array (
						'wp_quantity_hold' => $warehouse_product['wp_quantity_hold'] - $val['opm_quantity'],
						// 						'wp_status' => $warehouse_product['wp_quantity']==0&&$warehouse_product['wp_quantity_hold']==$val['opm_quantity']?0:1,
				);
				//异常判断
				if($warehouse_product_row['wp_quantity_hold']<0){
					throw new Exception("数据异常，订单：".$val['orders_code']." 货架库存 ".$warehouse_product['wp_id']." 冻结数量小于配货数");
				}
				if(!Warehouse_Service_Products::update($warehouse_product_row,$warehouse_product['wp_id'])){
					throw new Exception("数据异常，订单：".$val['orders_code']."货架库存 ".$warehouse_product['wp_id']." 更新失败");
				}
					
				//货架使用日志
				$WarehouseProductsLog = array(
						'wpl_refId' => $val['orders_code'],
						'user_id' => $user_id,
						'warehouse_id' => $warehouse_product['warehouse_id'],
						'ws_code' => $warehouse_product['ws_code'],
						'wpl_proc_type' => 0, //扣减库存
						'wpl_note' => '下架确认更改货架库存，冻结库存由'.$warehouse_product['wp_quantity_hold'].'变为'.$wp_quantity_hold."可用库存".$warehouse_product['wp_quantity'],
				);
				if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
					throw new Exception("订单：".$val['orders_code']." 货架 ".$warehouse_product['ws_code']." 写入使用日志失败失败");
						
				}
					
				//写入使用日志
				$addWSPU=array(
						'wpu_type'=>1,
						'wpu_proc_type'=>0,
						'wpu_refId'=>$val['orders_code'],
						'wpu_quantity'=>$val['opm_quantity'],
						'wpu_current_qty'=>$current_quantity,
						'wpu_note'=>'下架确认,可用库存：'.$ProBrow['wpb_quantity'].'冻结库存from:'.$ProBrow['wpb_quantity_hold']."to $current_quantity_hold",
						'wpb_id'=>$val['wpb_id'],
						'wpu_create_time'=>$date,
				);
				if(!Warehouse_Service_ProductUseage::create($addWSPU)){
					throw new Exception("订单：".$val['orders_code']." 写下架日志失败!");					
				}
			}else{
				throw new Exception("订单：".$val['orders_code']." 扣批次失败!");
				
			}
		}
		if(!$ordermodel->updateByOrdersCode(array('process_status'=>3),$order['orders_code'])){		
			throw new Exception("数据异常，订单 ".$ordersCode." 更新订单状态失败");		
		}
		
		return true;
		
	}
	//订单日志
	/*$remark 备注信息：如 订单下架，订单下架确认，订单出货，订单打包贴标，等等
	 * $frontShow 0:前台显示，1：后台显示
	 */
	public static  function createOrderLogNew($ordersCode,$old_orders_status,$old_process_status,$new_orders_status,$new_process_status,$remark="",$frontShow=0){
		$session = new Zend_Session_Namespace('userAuth');
		$userid=isset($session->userID)?$session->userID:0;
		
		$oshType = "";
		if(in_array($new_process_status,array(1,2,3,4))){
			$oshType = "Process";
			$status = $old_process_status;
		}elseif(in_array($new_process_status,array(5))){
			$oshType = "Shipping";
			$status = $old_process_status;
		}else{
			$oshType = "Revise";
			$status = $old_process_status;
		}
		$remark .= " orders_status from $old_orders_status".
				  " to $new_orders_status,process_status from $old_process_status to $new_process_status";
		$logRow = array (
				"orders_code" => $ordersCode,
				"osh_type" => $oshType,
				"osh_statu" => $status,
				"osh_statu_now" => $new_process_status,
				"osh_create_date" => date("Y-m-d H:i:s"),
				"osh_process_status"=>$frontShow,
				"osh_comments" => "order status ".$oshType,
				"osh_remark" => "[$ordersCode]".$remark,
				"user_id" => $userid,
				"osh_ip" => $_SERVER['REMOTE_ADDR'],
		);
		$model = new Order_Model_History();
		$model->create($logRow);
			
	}
	
	/*
	*判断是否投保
	*return true=>投保, false=>不投保
	*/
	 public function getInsurance(){
		if(strtoupper($this->_order['customer_id'])=='STK01'){
			return false;
		}
		return true;
	 }
}
